﻿using NewChillers.Models;
using NewChillers.Models.Events;
using NewChillers.Utils;
using SharpVectors.Dom.Svg;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using LiveCharts;
using LiveCharts.Wpf;
using LiveCharts.Defaults;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.Threading;

namespace NewChillers.ViewModels
{
    public class ManualControlViewModel : ObservableObject
    {
        //当前操作类型
        public enum CurrentOperationType
        {
            None,
            Heating,
            Vacuum,
            Helium,
            Exhaust
        }
        #region 属性
        private CancellationTokenSource _cts; // 令牌---加热
        private CancellationTokenSource _ctsVacuum;//令牌---抽真空
        private CancellationTokenSource _ctsPump;//令牌---充氦气
        private CancellationTokenSource _ctsEmit;//令牌---排气
        private CurrentOperationType _currentOperation = CurrentOperationType.None;
        private readonly DispatcherTimer _chartTimer;
        private readonly Dictionary<CurrentOperationType, ObservableCollection<string>> _timeLabelsDict;
        private readonly Dictionary<CurrentOperationType, ChartValues<ObservablePoint>> _valuesDict;
        private readonly Dictionary<CurrentOperationType, int> _dataPointIndexDict;
        private UserModel _currentUser;
        private readonly ShellViewModel _shellViewModel;

        // 图表相关属性
        public SeriesCollection SeriesCollection { get; set; }
        public IEnumerable<string> TimeLabels => _timeLabelsDict[CurrentOperation];
        public Func<double, string> YAxisLabelFormatter { get; set; }
        public string YAxisTitle { get; set; } = "数值";


        private string _heatValue;//加热文本输入框
        private string _btnHeatContent;
        private string _temperature;
        
        private string _drawValue;//抽真空文本输入框
        private string _btnDrawContent;
        private string _pressure;

        private string _pumpValue;//充氦气文本输入框
        private string _btnPumpContent;
        private string _precisePressure;

        private string _emitValue;//排气文本输入框
        private string _btnEmitContent;

        public string EmitValue
        {
            get { return _emitValue; }
            set
            {
                _emitValue = value;
                RaisePropertyChanged();
            }
        }

        public string BtnEmitContent
        {
            get { return _btnEmitContent; }
            set
            {
                _btnEmitContent = value;
                RaisePropertyChanged();
            }
        }

        public string PumpValue
        {
            get { return _pumpValue; }
            set
            {
                _pumpValue = value;
                RaisePropertyChanged();
            }
        }

        public string BtnPumpContent
        {
            get { return _btnPumpContent; }
            set
            {
                _btnPumpContent = value;
                RaisePropertyChanged();
            }
        }

        public string PrecisePressure
        {
            get { return _precisePressure; }
            set
            {
                _precisePressure = value;
                RaisePropertyChanged();
            }
        }

        public string Pressure
        {
            get { return _pressure; }
            set
            {
                _pressure = value;
                RaisePropertyChanged();
            }
        }

        public string DrawValue
        {
            get { return _drawValue; }
            set
            {
                _drawValue = value;
                RaisePropertyChanged();
            }
        }

        public string BtnDrawContent
        {
            get { return _btnDrawContent; }
            set
            {
                _btnDrawContent = value;
                RaisePropertyChanged();
            }
        }

        //private CurrentOperationType _currentManualStep;
        //public CurrentOperationType CurrentManualStep
        //{
        //    get => _currentManualStep;
        //    set => SetProperty(ref _currentManualStep, value);
        //}
        public CurrentOperationType CurrentOperation
        {
            get => _currentOperation;
            private set => SetProperty(ref _currentOperation, value);
        }

        public string Temperature
        {
            get { return _temperature; }
            set
            {
                _temperature = value;
                RaisePropertyChanged();
            }
        }

        public string BtnHeatContent
        {
            get { return _btnHeatContent; }
            set
            {
                _btnHeatContent = value;
                RaisePropertyChanged();
            }
        }
        public string HeatValue
        {
            get { return _heatValue; }
            set
            {
                _heatValue = value;
                RaisePropertyChanged();
            }
        }

        public ICommand BtnHeatCommand {get; set;}
        public ICommand BtnDrawCommand { get; set;}
        public ICommand BtnPumpCommand { get; set; }
        public ICommand BtnEmitCommand { get; set; }
        #endregion

        public ManualControlViewModel(UserModel userModel, ShellViewModel shellViewModel)
        {
            #region 默认值
            HeatValue = "100";
            BtnHeatContent = "加热";
            DrawValue = "10";
            BtnDrawContent = "抽真空";
            PumpValue = "5";
            BtnPumpContent = "充氦气";
            EmitValue = "0.01";
            BtnEmitContent = "排气";
            #endregion

            #region 初始化折线图字典数据
            // 初始化数据字典
            _timeLabelsDict = new Dictionary<CurrentOperationType, ObservableCollection<string>>
            {
                { CurrentOperationType.None, new ObservableCollection<string>() },
                { CurrentOperationType.Heating, new ObservableCollection<string>() },
                { CurrentOperationType.Vacuum, new ObservableCollection<string>() },
                { CurrentOperationType.Helium, new ObservableCollection<string>() },
                { CurrentOperationType.Exhaust, new ObservableCollection<string>() }
            };

            _valuesDict = new Dictionary<CurrentOperationType, ChartValues<ObservablePoint>>
            {
                { CurrentOperationType.None, new ChartValues<ObservablePoint>() },
                { CurrentOperationType.Heating, new ChartValues<ObservablePoint>() },
                { CurrentOperationType.Vacuum, new ChartValues<ObservablePoint>() },
                { CurrentOperationType.Helium, new ChartValues<ObservablePoint>() },
                { CurrentOperationType.Exhaust, new ChartValues<ObservablePoint>() }
            };

            _dataPointIndexDict = new Dictionary<CurrentOperationType, int>
            {
                { CurrentOperationType.None, 0 },
                { CurrentOperationType.Heating, 0 },
                { CurrentOperationType.Vacuum, 0 },
                { CurrentOperationType.Helium, 0 },
                { CurrentOperationType.Exhaust, 0 }
            };

            SeriesCollection = new SeriesCollection
            {
                new LineSeries
                {
                    Title = "实时数据",
                    Values = _valuesDict[CurrentOperationType.None],
                    PointGeometrySize = 10,
                    StrokeThickness = 2
                }
            };

            // 初始化Y轴标签格式化器和标题
            UpdateYAxisSettings();

            // 初始化定时器
            _chartTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1)
            };
            _chartTimer.Tick += OnChartTimerTick;
            #endregion

            BtnHeatCommand = new RelayCommand(HeatExcute);
            BtnDrawCommand = new RelayCommand(DrawExcuteAsync);
            BtnPumpCommand = new RelayCommand(PumpExcute);
            BtnEmitCommand = new RelayCommand(EmitExcute);
            _currentUser = userModel;
            _shellViewModel = shellViewModel;

            //CurrentManualStep = CurrentOperationType.None; // 步骤指示器

            // 订阅
            _shellViewModel.UserInfoUpdate += OnUserInfoUpdate;
        }


        #region 折线图
        // 更新Y轴设置的方法
        private void UpdateYAxisSettings()
        {
            switch (CurrentOperation)
            {
                case CurrentOperationType.Heating:
                    YAxisLabelFormatter = value => $"{value:F1}°C";
                    YAxisTitle = "温度(°C)";
                    break;
                case CurrentOperationType.Vacuum:
                    YAxisLabelFormatter = value => $"{value:F1}Pa";
                    YAxisTitle = "压强(Pa)";
                    break;
                case CurrentOperationType.Helium:
                    YAxisLabelFormatter = value => $"{value:F3}MPa";
                    YAxisTitle = "压力(MPa)";
                    break;
                case CurrentOperationType.Exhaust:
                    YAxisLabelFormatter = value => $"{value:F3}MPa";
                    YAxisTitle = "压力(MPa)";
                    break;
                default:
                    YAxisLabelFormatter = value => $"{value:F2}";
                    YAxisTitle = "数值";
                    break;
            }

            RaisePropertyChanged(nameof(YAxisLabelFormatter));
            RaisePropertyChanged(nameof(YAxisTitle));
        }

        // 切换当前操作类型的方法
        private void SwitchToOperation(CurrentOperationType operationType)
        {
            // 更新图表数据源
            ((LineSeries)SeriesCollection[0]).Values = _valuesDict[CurrentOperation];
            //_timeLabelsDict[_currentOperation] = new ObservableCollection<string>(_timeLabelsDict[_currentOperation]);
            CurrentOperation = operationType;

            // 在切换到新操作前，清空当前操作的数据
            if (CurrentOperation != CurrentOperationType.None)
            {
                ClearOperationData(CurrentOperation);
            }

            //_currentOperation = operationType;
            // 更新当前操作（步骤指示器会自动更新）
            CurrentOperation = operationType; // 是不是重复设置了？

            // 更新图表数据源
            ((LineSeries)SeriesCollection[0]).Values = _valuesDict[CurrentOperation];

            // 更新Y轴设置
            UpdateYAxisSettings();

            // 通知UI更新
            RaisePropertyChanged(nameof(TimeLabels));
        }

        // 图表定时更新处理方法
        private void OnChartTimerTick(object sender, EventArgs e)
        {
            var currentTime = DateTime.Now.ToString("HH:mm:ss");
            double currentValue = 0;

            // 根据当前操作类型获取相应数据
            switch (CurrentOperation)
            {
                case CurrentOperationType.Heating:
                    currentValue = DeviceDataStore.TemperatureValue_real;//加热
                    Temperature = $"{currentValue}°C";
                    break;
                case CurrentOperationType.Vacuum:
                    currentValue = DeviceDataStore.VacuumValue_real; //真空
                    Pressure = $"{currentValue}Pa";
                    break;
                case CurrentOperationType.Helium:
                    currentValue = DeviceDataStore.HeliumValue_real;//充氦气 
                    PrecisePressure = $"{currentValue}MPa";
                    break;
                case CurrentOperationType.Exhaust:
                    currentValue = DeviceDataStore.HeliumValue_real;//排气 
                    break;
                default:
                    return;
            }

            // 添加新的数据点
            _valuesDict[CurrentOperation].Add(new ObservablePoint(0, currentValue));

            // 添加时间标签
            _timeLabelsDict[CurrentOperation].Add(currentTime);

            // 控制数据点数量，避免图表过于拥挤
            while (_valuesDict[CurrentOperation].Count > 15)
            {
                _valuesDict[CurrentOperation].RemoveAt(0);
                _timeLabelsDict[CurrentOperation].RemoveAt(0);
            }

            // 更新所有数据点的X轴索引，使其连续
            for (int i = 0; i < _valuesDict[CurrentOperation].Count; i++)
            {
                var point = _valuesDict[CurrentOperation][i];
                _valuesDict[CurrentOperation][i] = new ObservablePoint(i, point.Y);
            }

            // 通知UI更新
            RaisePropertyChanged(nameof(TimeLabels));
        }

        // 添加清空数据的方法
        private void ClearOperationData(CurrentOperationType operationType)
        {
            if (_timeLabelsDict.ContainsKey(operationType))
            {
                _timeLabelsDict[operationType].Clear();
            }

            if (_valuesDict.ContainsKey(operationType))
            {
                _valuesDict[operationType].Clear();
            }

            // 重置数据点索引
            if (_dataPointIndexDict.ContainsKey(operationType))
            {
                _dataPointIndexDict[operationType] = 0;
            }
        }
        #endregion

        #region 加热
        /// <summary>
        /// 加热按钮点击事件
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private async void HeatExcute(object obj)
        {
            if (BtnHeatContent == "加热")
            {
                try
                {
                    var result = MessageBox.Show("是否开始加热?", "确认加热", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result != MessageBoxResult.Yes)
                    {
                        return;
                    }
                    BtnHeatContent = "取消";
                    _cts = new CancellationTokenSource();
                    var cancelToken = _cts.Token;
                    double doubleHeatValue = Convert.ToDouble(HeatValue);
                    if (doubleHeatValue > 100 || doubleHeatValue < 0)
                    {
                        MessageBox.Show("请输入0-100之间的数字", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else
                    {
                        await HeatUp(doubleHeatValue, cancelToken);
                        BtnHeatContent = "加热";
                        _chartTimer.Stop();
                        _cts.Cancel();
                        CurrentOperation = CurrentOperationType.None; // 加热完成，复位指示器
                        MessageBox.Show("加热完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                catch (OperationCanceledException)
                {
                    BtnHeatContent = "加热";
                    CurrentOperation = CurrentOperationType.None; // 取消加热，复位指示器
                }
                catch (Exception ex)
                {
                    _chartTimer.Stop();
                    _cts.Cancel();
                    BtnHeatContent = "加热";
                    MessageBox.Show("发送加热命令时发生错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                try
                {
                    // 添加取消加热确认提示框
                    var result = MessageBox.Show("是否取消加热?", "确认取消", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result != MessageBoxResult.Yes)
                    {
                        return; // 用户取消操作
                    }
                     _cts.Cancel();
                    _chartTimer?.Stop();
                    BtnHeatContent = "加热";
                    CurrentOperation = CurrentOperationType.None; // 取消加热，复位指示器
                }
                catch (Exception ex)
                {
                    MessageBox.Show("取消加热时发生错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 加热
        /// </summary>
        /// <param name="doubleHeatValue"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        private async Task HeatUp(double doubleHeatValue, CancellationToken cancelToken)
        {
            SwitchToOperation(CurrentOperationType.Heating);
            _chartTimer.Start();
            //加热
            while (!cancelToken.IsCancellationRequested)
            {
                Temperature = $"{DeviceDataStore.TemperatureValue_real}°C";
                if (DeviceDataStore.TemperatureValue_real >= doubleHeatValue)
                    return;

                await Task.Delay(200,cancelToken);
            }
        }

        #endregion

        #region 抽真空
        /// <summary>
        /// 抽真空按钮点击事件
        /// </summary>
        /// <param name="obj"></param>
        private async void DrawExcuteAsync(object obj)
        {
            if(BtnDrawContent == "抽真空")
            {
                try
                {
                    var result = MessageBox.Show("是否开始抽真空?", "确认抽真空", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result != MessageBoxResult.Yes)
                    {
                        return; // 用户取消操作
                    }
                    _ctsVacuum = new CancellationTokenSource();
                    var cancelToken = _ctsVacuum.Token;
                    BtnDrawContent = "取消";
                    _chartTimer.Start();
                    SwitchToOperation(CurrentOperationType.Vacuum);

                    await Draw(DrawValue,cancelToken);
                    BtnDrawContent = "抽真空";
                    _chartTimer.Stop();
                    _ctsVacuum.Cancel();
                    CurrentOperation = CurrentOperationType.None; // 抽真空完成，复位指示器
                    MessageBox.Show("抽真空完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }catch (OperationCanceledException)
                {
                    BtnDrawContent = "抽真空";
                    CurrentOperation = CurrentOperationType.None; // 取消抽真空，复位指示器
                }
                catch(Exception ex)
                {
                    BtnDrawContent = "抽真空";
                    _ctsVacuum.Cancel();
                    _chartTimer.Stop();
                    MessageBox.Show("抽真空时发生错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                try
                {
                    var result = MessageBox.Show("是否取消抽真空?", "确认取消", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result != MessageBoxResult.Yes)
                    {
                        return;
                    }
                    _chartTimer.Stop();
                    BtnDrawContent = "抽真空";
                    _ctsVacuum.Cancel();
                    CurrentOperation = CurrentOperationType.None; // 取消抽真空，复位指示器
                }
                catch (Exception ex)
                {
                    MessageBox.Show("取消抽真空时发生错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 抽真空
        /// </summary>
        /// <param name="drawValue"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        private async Task Draw(string drawValue, CancellationToken cancelToken)
        {
            double doubleDrawValue = Convert.ToDouble(drawValue);
            double initialVacuum = DeviceDataStore.VacuumValue_real;
            // 判断是否需要分阶段抽真空
            if (initialVacuum <= 10 && doubleDrawValue > 100)
            //if (initialVacuum > 10 && doubleDrawValue <= 10)
            {
                // 先用机械泵抽到10Pa，再启动分子泵继续抽到目标值
                await EvacuateVacuumStaged(doubleDrawValue, cancelToken);
            }
            else
            {
                // 直接抽真空到目标值
                string pumpType = doubleDrawValue >= 10 ? "机械泵" : "分子泵";
                await EvacuateVacuumDirect(doubleDrawValue, cancelToken, pumpType);
            }
        }

        /// <summary>
        /// 分阶段抽真空（先机械泵后分子泵）
        /// </summary>
        private async Task EvacuateVacuumStaged(double finalVacuumValue, CancellationToken cancellationToken)
        {
            // 第一阶段：使用机械泵抽到10Pa
            //打开机械泵+阀门

            await EvacuateVacuumDirect(10,cancellationToken, "机械泵");
            // 第二阶段：启动分子泵抽到最终目标值
            await EvacuateVacuumDirect(finalVacuumValue,cancellationToken, "分子泵");
            // 抽真空完成后关闭机械泵


        }

        /// <summary>
        /// 直接抽真空到目标值（带超时控制）
        /// </summary>
        private async Task EvacuateVacuumDirect(double vacuumValue,CancellationToken cancellationToken, string pumpType)
        {
            // 设置超时时间
            int timeoutSeconds = GetVacuumTimeout(vacuumValue);
            DateTime startTime = DateTime.Now;
            DateTime timeoutTime = startTime.AddSeconds(timeoutSeconds);

            // 持续抽真空直到达到目标值或被取消或超时
            while (!cancellationToken.IsCancellationRequested && DateTime.Now < timeoutTime)
            {
                double currentVacuum = DeviceDataStore.VacuumValue_real;
                Pressure = $"{DeviceDataStore.VacuumValue_real}MPa";
                // 检查是否达到目标真空度
                //测试是>=   实际 <=
                if (currentVacuum >= vacuumValue)
                {
                    return;
                }
                await Task.Delay(100, cancellationToken);
            }
            // 检查是否超时
            if (DateTime.Now >= timeoutTime && !cancellationToken.IsCancellationRequested)
            {
                double currentVacuum = DeviceDataStore.VacuumValue_real;
                string errorMsg = $"使用{pumpType}抽真空超时！目标: {vacuumValue}Pa，当前: {currentVacuum}Pa，超时时间: {timeoutSeconds}秒";
                throw new TimeoutException(errorMsg);
            }
        }

        /// <summary>
        /// 获取抽真空超时时间
        /// </summary>
        /// <param name="targetVacuum">目标真空度</param>
        /// <returns>超时时间（秒）</returns>
        private int GetVacuumTimeout(double targetVacuum)
        {
            // 根据技术规格设置超时时间
            if (targetVacuum >= 10)        // 大气压到 10Pa：≤5min
                return 5 * 60;
            else if (targetVacuum >= 1e-4) // 10Pa 到 10^-4Pa：≤25min
                return 25 * 60;
            else if (targetVacuum >= 5e-6) // 5x10^-4Pa 到 5x10^-5Pa：≤10min
                return 10 * 60;
            else
                return 60 * 60; // 默认1小时
        }
        #endregion

        #region 充氦气
        /// <summary>
        /// 充氦气按钮点击事件
        /// </summary>
        /// <param name="obj"></param>
        private async void PumpExcute(object obj)
        {
            if (BtnPumpContent == "充氦气")
            {
                try
                {
                    var result = MessageBox.Show("是否开始充氦气?", "确认充氦气", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result != MessageBoxResult.Yes)
                    {
                        return; // 用户取消操作
                    }

                    _ctsPump = new CancellationTokenSource();
                    var cancelToken = _ctsPump.Token;
                    BtnPumpContent = "取消";
                    _chartTimer.Start();
                    SwitchToOperation(CurrentOperationType.Helium);

                    double doublePumpValue = Convert.ToDouble(PumpValue);
                    if (doublePumpValue > 10 || doublePumpValue < 0)
                    {
                        MessageBox.Show("请输入0-10之间的数字", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else
                    {
                        await PumpHelium(doublePumpValue, cancelToken);
                        BtnPumpContent = "充氦气";
                        _chartTimer.Stop();
                        _ctsPump.Cancel();
                        CurrentOperation = CurrentOperationType.None; // 充氦气完成，复位指示器
                        MessageBox.Show("充氦气完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }catch(OperationCanceledException ex)
                {
                    BtnPumpContent = "充氦气";
                    CurrentOperation = CurrentOperationType.None; // 取消充氦气，复位指示器
                }
                catch (Exception ex)
                {
                    BtnPumpContent = "充氦气";
                    _chartTimer.Stop();
                    _ctsPump.Cancel();
                    MessageBox.Show("发送充氦气命令时发生错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                try
                {
                    var result = MessageBox.Show("是否取消充氦气?", "确认取消", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result != MessageBoxResult.Yes)
                    {
                        return; // 用户取消操作
                    }
                    _ctsPump.Cancel();
                    _chartTimer.Stop();
                    BtnPumpContent = "充氦气";
                    CurrentOperation = CurrentOperationType.None; // 取消充氦气，复位指示器
                }
                catch (Exception ex)
                {
                    MessageBox.Show("取消充氦气时发生错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        /// <summary>
        /// 充氦气
        /// </summary>
        /// <param name="pumpValue"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        private async Task PumpHelium(double pumpValue, CancellationToken cancelToken)
        {
            // 充氦气逻辑
            while (!cancelToken.IsCancellationRequested)
            {
                PrecisePressure = $"{DeviceDataStore.HeliumValue_real}MPa";
                if (DeviceDataStore.HeliumValue_real >= pumpValue)
                    return;

                await Task.Delay(200, cancelToken);
            }
        }

        #endregion

        #region 排气
        /// <summary>
        /// 排气按钮点击事件
        /// </summary>
        /// <param name="obj"></param>
        private async void EmitExcute(object obj)
        {
            if (BtnEmitContent == "排气")
            {
                try
                {
                    var result = MessageBox.Show("是否开始排气?", "确认排气", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result != MessageBoxResult.Yes)
                    {
                        return; // 用户取消操作
                    }

                    _ctsEmit = new CancellationTokenSource();
                    var cancelToken = _ctsEmit.Token;
                    BtnEmitContent = "取消";
                    _chartTimer.Start();
                    SwitchToOperation(CurrentOperationType.Exhaust);

                    double doubleEmitValue = Convert.ToDouble(EmitValue);
                    if (doubleEmitValue > 10 || doubleEmitValue < 0)
                    {
                        MessageBox.Show("请输入0-10之间的数字", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else
                    {
                        await EmitProcess(doubleEmitValue, cancelToken);
                        BtnEmitContent = "排气";
                        _chartTimer.Stop();
                        _ctsEmit.Cancel();
                        CurrentOperation = CurrentOperationType.None; // 排气完成，复位指示器
                        MessageBox.Show("排气完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                catch (OperationCanceledException)
                {
                    BtnEmitContent = "排气";
                    CurrentOperation = CurrentOperationType.None; // 取消排气，复位指示器
                }
                catch (Exception ex)
                {
                    BtnEmitContent = "排气";
                    _chartTimer.Stop();
                    _ctsEmit.Cancel();
                    MessageBox.Show("发送排气命令时发生错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                try
                {
                    var result = MessageBox.Show("是否取消排气?", "确认取消", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result != MessageBoxResult.Yes)
                    {
                        return; // 用户取消操作
                    }
                    _ctsEmit.Cancel();
                    _chartTimer.Stop();
                    BtnEmitContent = "排气";
                    CurrentOperation = CurrentOperationType.None; // 取消排气，复位指示器
                }
                catch (Exception ex)
                {
                    MessageBox.Show("取消排气时发生错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        // <summary>
        /// 排气过程
        /// </summary>
        /// <param name="emitValue"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        private async Task EmitProcess(double emitValue, CancellationToken cancelToken)
        {
            // 排气逻辑
            while (!cancelToken.IsCancellationRequested)
            {
                // 检查是否达到目标压力值
                if (DeviceDataStore.HeliumValue_real <= emitValue)
                    return;

                await Task.Delay(200, cancelToken);
            }
        }

        #endregion

        #region 更新当前登录用户的信息 事件处理
        /// <summary>
        /// 接收到通知
        /// </summary>
        private void OnUserInfoUpdate(object sender, UserInfoUpdateEventArgs e)
        {
            // 空值检查，避免NullReferenceException
            if (e?.UpdatedUser != null)
            {
                _currentUser = e.UpdatedUser;
                Debug.WriteLine("ManualControl页面|用户信息已更新");
            }
            else
            {
                Debug.WriteLine("收到空的事件参数");
            }
        }

        /// <summary>
        /// 析构函数中的事件取消订阅
        /// </summary>
        ~ManualControlViewModel()
        {
            _chartTimer?.Stop();
            CurrentOperation = CurrentOperationType.None; // 确保退出时复位
            _shellViewModel.UserInfoUpdate -= OnUserInfoUpdate;
        }
        #endregion


    }
}
